// 引入express模块
const express = require('express')

// 引入path模块
const path = require('path')
// 创建服务
const app = express()

// 解析前端传来的token
const expressJWT = require('express-jwt')
// 获取秘钥
const config = require('./auth/config')

const Response = require('./utils/ResponseData')
const Content = require('./utils/Content')

// 配置jwt拦截规则
app.use(expressJWT({ secret: config.secretKey }).unless({ path: ['/adminLogin', /^\/user/] }))

// 配置内容解析器
const bodyParser = require('express')
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())

// 使用错误处理中间件，拦截所有路由中抛出的异常
app.use((err, req, res, next) => {
    // token校验不通过提示
    if (err.name == 'UnauthorizedError') {
        return res.send(Response.error('token已失效，请重新登录', Content.AUTH_ERROR))
    }
    res.send(Response.error('服务器异常，请重新访问服务器', 500))
    next()
})

// 导入相关路由文件
const petAdmin = require('./routes/admin/PetAdmin')
const petBusiness = require('./routes/admin/PetBusiness')
const petDairy = require('./routes/admin/PetDairy')
const petOrder = require('./routes/admin/PetOrder')
const petUser = require('./routes/admin/PetUser')
const userRouter = require('./routes/user/User')
const dailyRouter = require('./routes/user/Daily')
const busRouter = require('./routes/user/Bus')
const contactRouter = require('./routes/user/Contact')
// 使用路由

app.use(petAdmin)
app.use(petBusiness)
app.use(petDairy)
app.use(petOrder)
app.use(petUser)
app.use('/user', userRouter)
app.use('/daily', dailyRouter)
app.use('/bus', busRouter)
app.use('/contact', contactRouter)


// 托管静态资源文件
app.use(express.static('./public'))
app.use(express.static(path.join(__dirname, 'public')))



// 启动服务器
app.listen(3000, () => {
    console.log('服务器启动成功：', 'http://localhost:3000')
})

// 拦截前端请求错误
const history = require('connect-history-api-fallback')

app.use(history())